<?php
header('Access-Control-Allow-Origin: *');
$root = $_SERVER['DOCUMENT_ROOT'] . "/php/";

include_once "$root/class/UserManager.php";
include_once "$root/class/User.php";
include_once "$root/class/FileUpload.php";
include_once "$root/class/NetSign.php";
include_once "$root/class/CardKeyManager.php";
include_once "$root/class/CardKey.php";

date_default_timezone_set("PRC");
session_start();
function getUid()
{
    if (!empty($_GET["id"])) {
        return $_GET["id"];
    }

    if (!empty($_SESSION["uid"])) {
        return $_SESSION["uid"];
    } else {
        $arr = array();
        $arr["state"] = "false";
        $arr["code"] = "1000";
        die(json_encode($arr));
    }
}

function resultCode($state = "true", $code = 0000)
{
    $arr = array();
    $arr["state"] = $state;
    $arr["code"] = $code;
    return json_encode($arr);
}

$netSign = new NetSign($_GET["s"]);

if (!$netSign->verifySign()) {
    echo resultCode(false, 1000);
    return;
}
$type = $_GET["type"];
if (empty($type)) {
    die("type Error");
}
$userManager = new UserManager();
$eggUtil = new EggUtil();

switch ($type) {
    /**
     * 添加用户
     * @Methods POST
     *
     * @Params q
     *  用户QQ
     * @Params e
     * 用户邮箱
     * @Params n
     * 用户昵称
     */

    case "au":
        if (empty($_POST["u"]) || empty($_POST["p"] || empty($_POST["q"]) || empty($_POST["e"]) || empty($_POST["n"]))) {
            echo "参数不能为空";
            return;
        }
        $arr = array();
        $arr["user"] = $_POST["u"];
        $result = $userManager->queryUser($arr);

        if (count($result) != 0) {

            die("用户已注册");
        }

        $arr = array();
        $user = new User();

        $user->setUniversal();
        $user->setQq($_POST["q"]);
        $user->setUNum($_POST["u"]);
        $user->setUPass(md5($_POST["p"]));
        $user->setEmail($_POST["e"]);
        $user->setName($_POST["n"]);
        $user->setHeadIcon("false");
        $user->setUserTargetTime(new UserDate());

        $isOk = $userManager->putUserData($user);

        echo $eggUtil->isOk($isOk);
        break;
    /**
     * 登录
     */
    case "du":
        if (empty($_POST["u"]) || empty($_POST["p"])) {
            echo "参数不能为空";
            return;
        }
        $arr = array();
        $arr["user"] = $_POST["u"];
        $result = $userManager->queryUser($arr)[0];
        if (!($result["user"] == $_POST["u"] && $result["pass"] == md5($_POST["p"]))) {
            echo "用户不存在";
        } else {
            $_SESSION["uid"] = $result["Id"];
            echo "成功";
        }
        break;

    case "ed":
        unset($_SESSION["user"]);
        echo "已退出";
        break;
    /**
     * 删除用户
     * @Methods GET
     * @Params id
     * 用户ID
     */
    case "ru":
        $userManager->setCurrentId(getUid());
        echo $eggUtil->isOk($userManager->removeUser());
        break;

    /**
     * 查看指定用户
     * @Methods GET
     * @Params id
     * 用户ID
     */
    case "gu":
        $userManager->setCurrentId(getUid());

        $result = $userManager->getUser();
        if ($result) {
            echo json_encode($result[0]);
        } else {
            echo $eggUtil->isOk($result);
        }
        break;

    /**
     * 查询数据
     * @Methods GET
     *
     * @Params fie
     * 数据库字段名字
     * @Params val
     * 字段值
     */
    case "qu":
        $arr = array();
        $arr[$_GET["fie"]] = $_GET["val"];
        $result = $userManager->queryUser($arr);
        if ($result) {
            echo json_encode($result);
        } else {
            echo $eggUtil->isOk($result);
        }
        break;

    /**
     * 修改用户
     * @Methods POST
     *
     * @Params fie
     * 数据库字段名字
     * @Params val
     * 字段值
     */
    case "lu":
        $arr = array();
        $arr[$_POST["fie"]] = $_POST["val"];
        echo $eggUtil->isOk($userManager->alterUser(getUid(), $arr));
        break;

    /**
     * 上传文件
     * @Methods POST
     *
     * @Params id
     * 用户ID
     */
    case "uf":
        $userManager->setCurrentId(getUid());
        $fileUpload = new FileUpload($userManager);
        echo $eggUtil->isOk($fileUpload->upload($_FILES["file"], array("png", "jpg")));
        break;

    /**
     * 删除文件
     * @Methods GET
     *
     * @Params id
     * 用户ID
     * @Params fid
     * 文件ID
     */
    case "df":
        $userManager->setCurrentId(getUid());
        $fileUpload = new FileUpload($userManager);
        echo $eggUtil->isOk($fileUpload->removeFile($_GET["fid"]));
        break;
    /**
     * 升级为VIP
     * @Methods POST
     *
     * @Paeams id
     * 用户ID
     */
    case "pm":
        $per = array();
        $arr = array();
        $userManager->setCurrentId(getUid());
        $userResult = $userManager->getUser()[0];
        $per = json_decode($userResult["permissions"], true);
        $per["type"] = UserManager::$MEMBER;
        $userDate = new UserDate($per["time"]);
        $userDate->plusTime(UserDate::$MONTH);
        $per["time"] = $userDate->getTarGetTime();
        $arr["permissions"] = json_encode($per);
        echo $eggUtil->isOk($userManager->alterUser(getUid(), $arr));
        break;

    /**
     * 加会员时间
     * @Methods POST
     * @Params id
     * 用户id
     * @Params time
     * 要加多久 （精度：1/秒）
     */
    case "at":
        if (!is_numeric($_POST["time"])) {
            die("格式错误");
        }
        $per = array();
        $arr = array();
        $userManager->setCurrentId(getUid());
        $userResult = $userManager->getUser()[0];
        $per = json_decode($userResult["permissions"], true);
        $userDate = new UserDate($per["time"]);
        $userDate->plusTime($_POST["time"]);
        $per["time"] = $userDate->getTarGetTime();
        $arr["permissions"] = json_encode($per);
        echo $eggUtil->isOk($userManager->alterUser(getUid(), $arr));
        break;
    /**
     * 获取所有用户
     */
    case "lsu":
        echo json_encode($userManager->listUser());
        break;
    /**
     * 上传头像
     * @Methods POST
     *
     * @Params id
     * 用户id
     * $Params
     * 上传文件
     */
    case "uic":
        $userManager->setCurrentId(getUid());
        $fileUpload = new FileUpload($userManager);
        echo $eggUtil->isOk($fileUpload->uploadIcon($_FILES["file"]));
        break;
    case "su":
        $userManager->setCurrentId(getUid());
        $result = $userManager->getUser()[0];
        $t = json_decode($result["permissions"], true)["time"];
        if ($t < time()) {
            $dateStr = "未开通";
        } else {
            $dateStr = date("Y-m-s H:i:s", $t);
        }

        $result["perState"] = $dateStr;
        echo json_encode($result);
        break;

    /**
     * 使用卡密
     */
    case "uk":


        if (empty($_GET["k"])) {
            echo "参数不能为空";
            return;
        }
        $val = array();
        $cardKeyManager = new CardKeyManager();
        $userManager->setCurrentId(getUid());

        $userD = $userManager->getUser()[0];
        $cardResult = $cardKeyManager->getCardKey($_GET["k"])[0];
        if (!$cardKeyManager->removeKey($_GET["k"])) {
            echo "卡密已使用";
            return;
        }

        $per = json_decode($userD["permissions"], true);
        $userDate = new UserDate($per["time"]);
        $userDate->plusTime($cardResult["time"]);
        $per["time"] = $userDate->getTarGetTime();
        $val["permissions"] = json_encode($per);
        if ($userManager->alterUser(getUid(), $val)) {
            echo "使用成功";
        } else {
            echo "使用失败";
        }

        break;
    case "huifu":
        $p = "../user/xiaonian/user";
        foreach (scandir($p) as $v) {
            if (!($v == "." or $v == "..")) {
                $d = "$p/$v";
                if (is_dir($d)) {
                    $arr = array();
                    $user = new User();
                    $user->setUniversal();
                    $user->setQq(file_get_contents("$d/qq.txt"));
                    $user->setUNum(file_get_contents("$d/user.txt"));
                    $user->setUPass(file_get_contents("$d/pass.txt"));
                    $user->setEmail("11110@qq.com");
                    $user->setName(file_get_contents("$d/name.txt"));
                    $user->setHeadIcon("false");
                    if (file_get_contents("$d/vip.txt") != "no") {
                        $user->setMember();
                    }
                    $userDate = new UserDate((int)substr(file_get_contents("$d/viptime.txt"), 0, 10));
                    $user->setUserTargetTime($userDate);
                    $isOk = $userManager->putUserData($user);
                    echo file_get_contents("$d/viptime.txt") . "\n";
                }
            }
        }
        break;
    default:
        die("Error");
}




/*
        垃圾场



    case "t":
        $p = "./user/xiaonian/user";
        foreach (scandir($p) as $v) {
            if (!($v == "." or $v == "..")) {
                $d = "$p/$v";
                if (is_dir($d)) {
                    $arr = array();
                    $user = new User();
                    $user->setUniversal();
                    $user->setQq(file_get_contents("$d/qq.txt"));
                    $user->setUNum(file_get_contents("$d/user.txt"));
                    $user->setUPass(file_get_contents("$d/pass.txt"));
                    $user->setEmail("11110@qq.com");
                    $user->setName(file_get_contents("$d/name.txt"));
                    $user->setHeadIcon("false");
                    if (file_get_contents("$d/vip.txt") != "no") {
                        $user->setMember();
                    }
                    $userDate = new UserDate((int)substr(file_get_contents("$d/viptime.txt"), 0, 10));
                    $user->setUserTargetTime($userDate);
                    $isOk = $userManager->putUserData($user);
                    echo file_get_contents("$d/viptime.txt") . "\n";
                }
            }
        }

        break;



        $arr["name"] = "te";
        $arr["qq"] = "qqs";
        $arr["email"] = "emaile";
        $arr["permissions"]["type"] = "";
*/